<?php
/**
 * Server refreshing ranking and newest videos in an interval
 */
 
$CURRENT_PATH = dirname(__FILE__).DIRECTORY_SEPARATOR;
require_once($CURRENT_PATH."setup.php");
require_once(CONTROLLER_PATH.'mikubook.controller.php');
$running = true;

$c = new Mikubook_Video_Controller();
Mikubook_Video_Controller::$LOGIN = SERVER_MIKUBOOK_LOGIN;
Mikubook_Video_Controller::$PASSWORD = SERVER_MIKUBOOK_PASSWORD;

$connection_errors = array(
	'invalid_mail' => 'Invalid mail address or password',
	'invalid_mail_password' => 'Invalid mail address or password',
	'password_too_long' => 'Please enter your password more shortly',
	'need_password_or_login' => 'Please enter your mail address or password'
);


function output($mes, $error = false) {
	if (!$error) {
		echo "[Log";
	}
	else {
		echo "[Error";
	}
	echo " - ".date('d/m/Y H:i:s')."] $mes\n";
}

while($running) {
	$c->resetConnection();
	if (!$c->connected) {
		$error = $c->error_connection;
		if (isset($connection_errors[$error])) {
			$error = $connection_errors[$error];
		}
		output("Connection failed with credentials ".SERVER_MIKUBOOK_LOGIN." / ******", true);
		output("Message: ".$error,true);
		$running = false;
	}
	else {
		output("Refreshing ranks");
		$c->getVideos(array('ranktype' => 'day'));
		output("Data top of the day cached.");
		$c->getVideos(array('ranktype' => 'week'));
		output("Data top of the week cached.");
		$c->getVideos(array('ranktype' => 'all'));
		output("Data top general cached.");
		$c->getVideos(array('newest' => true));
		output("Newest videos cached.");
		output("Waiting ".date('d/m/Y H:i:s', (time()+SERVER_REQUEST_INTERVAL))." to refresh...");
		sleep(SERVER_REQUEST_INTERVAL);
	}
}
?>